package com.wu.demo.farmework.manager;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.wu.demo.common.domain.RequestMonitorVo;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther: wu
 * @Date: 2024/3/11
 * @Description: 统计接口访问成功失败信息
 */
@Slf4j
public class RequestCounter {

    /**
     * guava cache缓存接口访问记录
     */
    private static Cache<String,  RequestMonitorVo> cache= CacheBuilder.newBuilder()
            .expireAfterWrite(60 * 15, TimeUnit.SECONDS) //过期策略，15分钟刷新
            .build();

    /**
     * 获取接口计数统计vo
     */
    public static RequestMonitorVo getRequestMonitor(String key){
        RequestMonitorVo vo = cache.getIfPresent(key);
        if(vo == null){
            vo = new RequestMonitorVo();
            String[] split = key.split("--");
            vo.setTime(split[0]);
            vo.setRequestUrl(split[1]);
        }
        return vo;
    }

    /**
     * 增加接口调用成功相关统计
     */
    public static void increaseSuccessInfo(String key,Long successTime){
        RequestMonitorVo vo = getRequestMonitor(key);
        Lock lock = new ReentrantLock();
        lock.lock();
        try {

            Long successMaxTime = vo.getSuccessMaxTime();
            successMaxTime = successMaxTime > successTime ? successMaxTime : successTime;
            vo.setSuccessMaxTime(successMaxTime);
            vo.setSuccessTotalTime(vo.getSuccessTotalTime() + successTime);
            vo.setSuccessNum(vo.getSuccessNum() + 1);
            cache.put(key,vo);
        }catch (Exception e){
            log.error("---increaseSuccess,exception:",e);
        }finally {
            lock.unlock();
        }
    }

    /**
     * 增加接口调用成功相关统计
     */
    public static void increaseFailInfo(String key,Long failTime){
        RequestMonitorVo vo = getRequestMonitor(key);
        Lock lock = new ReentrantLock();
        lock.lock();
        try {
            vo.setFailTotalTime(vo.getFailTotalTime() + failTime);
            vo.setFailNum(vo.getSuccessNum() + 1);
            cache.put(key,vo);
        }catch (Exception e){
            log.error("---increaseFailInfo,exception:",e);
        }finally {
            lock.unlock();
        }
    }

    /**
     * 获取时间戳，并以5分钟为一个节点进行统计 如：0,5,15,20.......
     * @return
     */
    public static String getTimeStamp(){
        Long millis = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
        SimpleDateFormat sdfMinute = new SimpleDateFormat("mm");//时间戳转换成时间字符串
        String dated = sdf.format(new Date(Long.parseLong(String.valueOf(millis))));//时间戳转换成时间字符串
        String minute = sdfMinute.format(new Date(Long.parseLong(String.valueOf(millis))));
        dated += ":"+ (Integer.valueOf(minute) - Integer.valueOf(minute) % 5);
        return dated;
    }

    public static CopyOnWriteArrayList<RequestMonitorVo> getCacheInfo(){
        CopyOnWriteArrayList<RequestMonitorVo> list = new CopyOnWriteArrayList<>();
        ConcurrentMap<String,RequestMonitorVo> maps = cache.asMap();
        for (RequestMonitorVo value : maps.values()) {
            list.add(value);
        }
        return list;
    }
}
